/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2012 www.pretty-tools.com
 */

/**
 * Web Page Profile
 */

/**
 * Profile Merger.
 *
 * @author Alexander Kozlov
 */
var wsshWebProfileMergeHelper = {
    logger: yrprxFactory.createLogger("wsshWebProfileMergeHelper")
};

// will throw exeption on merge error
wsshWebProfileMergeHelper.merge = function(oldProfile, newProfile)
{
    this.logger.debug("merge");
    // ivalid input
    if (!oldProfile && !newProfile)
        return new Array();
    // there is no rules
    if (!oldProfile.length)
        return newProfile;
    // new profile is invalid
    if (!newProfile.length)
        return oldProfile;

    // let's merge it

    var merged = this.cloneProfile(oldProfile);

    // copy new rules
    for (var k in newProfile)
    {
        var profile = newProfile[k];
        if (!profile || !profile.pages)
            continue;

        var idx = this.findDomain(merged, profile.domain);
        if (idx == -1)
            merged.push(profile);
        else // copy or update
        {
            var pages = merged[idx].pages;

            for (var t in profile.pages)
            {
                var page = profile.pages[t];
                if (!page) continue;

                var x = this.findPage(pages, page);
                if (x == -1)
                    pages.push(page);
                else
                    pages[x] = page;
            }
        }
    }

    return merged;
}

wsshWebProfileMergeHelper.cloneProfile = function(items)
{
    var cloned = new Array();

    // copy/clone rules
    for (var i in items)
    {
        var profile = items[i];
        if (!profile || !profile.pages)
            continue;

        cloned.push(profile.clone());
    }

    return cloned;
}

wsshWebProfileMergeHelper.findPage = function(pages, page)
{
    try
    {
        var pagePattern = page.pattern.source.toLowerCase();

        for (var i in pages)
        {
            if (!pages[i])
                continue;

            if (pagePattern == pages[i].pattern.source.toLowerCase())
                return i;
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("findPage: Exception: " + ex);
    }
    return -1;
}

wsshWebProfileMergeHelper.findDomain = function(profile, domain)
{
    try
    {
        domain = domain.toLowerCase();

        for (var i in profile)
        {
            if (!profile[i])
                continue;

            if (domain == profile[i].domain.toLowerCase())
                return i;
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("findDomain: Exception: " + ex);
    }
    return -1;
}
